/****************************************************
 * Description: 登录管理类
 * Copyright:   Copyright (c) 2013
 * Company:     beiwaionline
 * @author      caoxl
 * @version     1.0
 * @see
	HISTORY
	*  2013-07-23 caoxl Create File
	*  2013-08-26 zhanghejie modify 超级管理员，和管理员和教师分别使用三个不同的登陆页面。 
**************************************************/
package com.bfsuol.common.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bfsuol.common.Constants;
import com.bfsuol.common.service.LoginService;
import com.bfsuol.common.util.BaseUtils;
import com.bfsuol.common.util.BfsuMessage;
import com.bfsuolcomponents.log.BfsuolLogger;
import com.bfsuolframework.security.entity.BaseUser;
import com.bfsuolframework.security.entity.Group;
import com.bfsuolframework.security.entity.GroupRole;
import com.bfsuolframework.security.entity.Role;
import com.bfsuolframework.core.BfsuolConstants;
import com.bfsuolframework.core.controller.LoginInfo;
import com.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuolframework.core.exception.ValidationException;
import com.bfsuolframework.core.utils.EncryptUtils;
import com.bfsuolframework.core.utils.FreemarkerUtils;
import com.bfsuolframework.core.utils.MailUtils;
/**
 * 登录相关功能管理
 * @author caoxl
 */
@Controller
@RequestMapping("/login")
public class LoginController  extends SpringControllerSupport {
	
	@Autowired
	private LoginService loginService;
	
	/**
	 * 用户登录页
	 * @return
	 */
	@RequestMapping("/login")
	public String login(){
		return "/common/login/login";
	}

	/**
	 * 用户登录
	 * @param base
	 * @param model
	 * @return
	 */
	@RequestMapping("/logon")
	public String logon(@RequestParam String loginname,@RequestParam String password,Model model){

		String msg=validateLogin(loginname,password);
		model.addAttribute("loginname",loginname);
		if(msg!=null){
			model.addAttribute("loginErrInfo",msg);
			return "/common/login/login";
		}
		
		password = EncryptUtils.MD5Encode(password);//MD5密码加密
		
		BaseUser baseUser = loginService.getBaseUserByLogin(loginname, password);
		if(baseUser!=null){
			baseUser.setLastLoginIp(BaseUtils.getClientIp(getRequest()));
			baseUser.setLastLoginTime(new Date());
			baseUser.setLoginCount(baseUser.getLoginCount()==null?1:baseUser.getLoginCount()+1);
			loginService.update(baseUser);
			LoginInfo loginInfo = new LoginInfo();
			loginInfo.setLoginName(baseUser.getLoginName());
			loginInfo.setUserId(baseUser.getId());
			loginInfo.setUserName(baseUser.getUserName());
			loginInfo.setUserType(baseUser.getUserType());
			
			
			
			List<String> roleCodeList=new ArrayList<String>();
			//用户组默认角色
			if(baseUser.getGroups()!=null){
				for(Group group : baseUser.getGroups()){
					if(group.getRoles()!=null&&group.getRoles().size()>0){
						for(GroupRole role:group.getRoles()){
							if(role.getIsDefault()!=null&&role.getIsDefault().equals(BfsuolConstants.GLOBAL_YESNO_YES)){
								roleCodeList.add(role.getRole().getCode());
							}
						}
					}
				}
			}
			if(baseUser.getRoles()!=null&&baseUser.getRoles().size()>0){
				for(Role role:baseUser.getRoles()){
					roleCodeList.add(role.getCode());
				}
				
			}
			if(roleCodeList.size()>0){
				String[] roleCodes=new String[roleCodeList.size()];
				int i=0;
				for(String s:roleCodeList){
					roleCodes[i]=s;
					i++;
				}
				loginInfo.setRoleCodes(roleCodes);
			}
		
			getRequest().getSession().setAttribute(BfsuolConstants.SESSION_LOGININFO_KEY,loginInfo);
			BfsuolLogger.data("用户登录，用户名："+baseUser.getLoginName());
			
			if(Constants.USER_TYPE_LEARNER.equals(baseUser.getUserType())){
				return "redirect:/lms/fore/foreCourse/courseList";				
			}else{
				return "redirect:/index/managerIndex";				
			}
		}else{
			model.addAttribute("loginErrInfo","用户名或密码有误");
			return "/common/login/login";
		}
	}
	/**
	 * 用户登出
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(){
		LoginInfo loginInfo = (LoginInfo) getRequest().getSession().getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		if(loginInfo!=null){
			BaseUser baseUser = loginService.getById(loginInfo.getUserId());
			if(baseUser!=null){
				loginInfo.updateLastBrowseTime();
				baseUser.setOnlineTime(baseUser.getOnlineTime()==null?0:baseUser.getOnlineTime()+loginInfo.getOnlineSeconds());
				loginService.update(baseUser);
				//BfsuolLogger.data("用户退出，用户名："+baseUser.getLoginName());
			}

			
			getRequest().getSession().removeAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);			
		}
		return "redirect:/login/login";
		
	}
	/**
	 * 验证登录信息
	 * @param base
	 */
	public String validateLogin(String loginname,String password){
		if(loginname==null||loginname.trim().length()==0){
			return "登录名不能为空";
		}
		if(password==null||password.trim().length()==0){
			return "密码不能为空";
		}
		return null;
	}

	/**
	 * 密码重置页面
	 * @param baseUser
	 * @param model
	 * @return
	 */
	@RequestMapping("/toResetPassword")
	public String toResetPassword(@ModelAttribute BaseUser baseUser, Model model) {
		return "/common/login/password-reset";
	}
	
	/**
	 * 密码重置
	 * @return
	 */
	@RequestMapping("/passwordReset")
	public @ResponseBody MessageJson passwordReset(@ModelAttribute BaseUser baseUser,Model model) {
		BaseUser base = loginService.getBaseUserByEmail(baseUser.getLoginName(),baseUser.getEmail());
		if(base!=null){
			String newPwd = getRandomString(10);//获取10位随机密码
			base.setPassword(EncryptUtils.MD5Encode(newPwd));
			loginService.update(base);
			//BfsuolLogger.data("密码重置，用户名：",base.getLoginName());
			//发送邮件
			String message = FreemarkerUtils.getMessage(
					BfsuMessage.EMAIL_RESETPWD_BODY,
					FreemarkerUtils.getModel().add("userName", base.getLoginName())
					.add("password", newPwd).toMap());
			boolean isSendSuccess = MailUtils.sendHtmlMail(base.getEmail(), null, null, BfsuMessage.EMAIL_RESETPWD_TITLE, message, false);
			if(isSendSuccess){
				return MessageJson.information("重置密码已经发送到您的邮箱！请及时登录更改密码！");
			}else{
				throw new ValidationException( "发送失败，请检查邮箱是否正确");
			}
		}else{
			throw new ValidationException( "该用户名与注册时的邮箱不匹配！");
		}
	}
	
	
	/**
	 * 获得指定长度的随机字符串
	 * @param length
	 * @return
	 */
	public String getRandomString(int length) { 
	    StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); 
	    StringBuffer sb = new StringBuffer(); 
	    Random r = new Random(); 
	    int range = buffer.length(); 
	    for (int i = 0; i < length; i ++) { 
	        sb.append(buffer.charAt(r.nextInt(range))); 
	    } 
	    return sb.toString(); 
	}
	
}
